package com.jacky.service.impl;

import com.jacky.po.AbstractUser;
import com.jacky.service.FileService;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;

import java.io.*;

/**
 * @Description: 文件操作服务接口的实现类
 * @author: Jacky
 * @date: 2021.10.13
 */
public class FileServiceImpl implements FileService {

    private final static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Override
    public String[] fileReading(File file){
        if(file.exists()){
            try (BufferedReader br = new BufferedReader(new FileReader(file))){
                String len=null;
                StringBuilder strs = new StringBuilder();
                while ((len = br.readLine())!=null){
                    strs.append(len+"\n");
                }
                return strs.toString().split("\n");
            } catch (FileNotFoundException e) {
                logger.error("找不到读取文件路径",e);
            } catch (IOException e) {
                logger.error("文件读取失败",e);
            }
        }else {
            System.out.println("用户文件不存在");
        }
        return null;
    }

    @Override
    public boolean fileWriting(File file,AbstractUser user) {
        if ("".equals(user.getName())|| "".equals(user.getPassword())||"".equals(user.getIdentity())) {
            System.out.println("账号或密码输入为空，注册失败");
        }else {
            try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,true)))) {
                writer.write("username:" + user.getName()+"&password:"+user.getPassword()+"&identity:"+user.getIdentity()+"\n");
                return true;
            } catch (FileNotFoundException e) {
                System.out.println("找不到读取文件路径");
                logger.error("找不到读取文件路径",e);
            } catch (IOException e) {
                System.out.println("文件写入失败");
                logger.error("文件写入失败",e);
            }
        }
        return false;
    }
}
